package com.apobates.jforum2.troll.nest.controller;

import com.apobates.jforum2.troll.accounts.stub.CommonResponseVo;
import com.apobates.jforum2.troll.accounts.stub.vo.MemberModelVo;
import com.apobates.jforum2.troll.accounts.stub.vo.MemberOnlineVo;
import com.apobates.jforum2.troll.accounts.stub.vo.MemberProfileVo;
import com.apobates.jforum2.troll.accounts.stub.vo.MemberRecordVo;
import com.apobates.jforum2.troll.accounts.stub.vo.MemberSocialVo;
import com.apobates.jforum2.troll.accounts.stub.vo.MemberStatsCollectVo;
import com.apobates.jforum2.troll.accounts.stub.vo.MemberVo;
import com.apobates.jforum2.troll.actionlog.stub.vo.ThreadsStatsCollectVo;
import com.apobates.jforum2.troll.nest.service.ActionLogClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.apobates.jforum2.troll.nest.service.MemberClient;
import com.apobates.jforum2.troll.regular.ForumActionEnum;
import com.google.gson.Gson;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 会员服务API控制器
 * 注意: 需要带有服务响应的状态码使用ResponseEntity, 对于返回值对象的请求在失败时返回404,对于String响应的操作返回401
 * @author xiaofanku
 * @since 20210412
 */
@RestController
@RequestMapping("/api/member")
public class MemberClientController {
    @Autowired
    private MemberClient memberClient;
    @Autowired
    private ActionLogClient actionLogClient;
    private final static Logger logger = LoggerFactory.getLogger(MemberClientController.class);

    //1:查看指定会员
    @GetMapping("/{id}")
    public MemberVo get(@PathVariable("id")long memberId){
        ResponseEntity<MemberVo> mv = memberClient.get(memberId);
        return Optional.ofNullable(mv.getBody()).orElse(new MemberVo());
    }
    //8:会员在线记录
    @GetMapping("/online/{member}")
    public MemberOnlineVo getOnlineRecord(@PathVariable("member") long memberId){
        ResponseEntity<MemberOnlineVo> rs = memberClient.getOnlineRecord(memberId);
        return Optional.ofNullable(rs.getBody()).orElse(new MemberOnlineVo());
    }
    
    //9:会员话题操作统计信息
    @GetMapping("/stats/{member}")
    public ThreadsStatsCollectVo getMemberActionStats(@PathVariable("member") long memberId){
        ResponseEntity<ThreadsStatsCollectVo> rs = actionLogClient.getTopicActionStats(memberId);
        return Optional.ofNullable(rs.getBody()).orElse(new ThreadsStatsCollectVo());
    }
    
    //10:保存在线记录
    @PostMapping(value="/online/create", consumes="application/json; charset=utf-8")
    public ResponseEntity<String> createOnlineRecord(@RequestBody MemberOnlineVo mov){
        try {
            return memberClient.createOnlineRecord(mov);
        }catch (Exception e){
            logger.error("[nest-member-online]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.badRequest().build();
    }
    
    //11:个人信息(通过txt/传递)
    @GetMapping("/{id}/profile")
    public ResponseEntity<MemberProfileVo> getMemberProfile(@PathVariable("id") long memberId){
        Map<ForumActionEnum, Long> topicActionStats = actionLogClient.getTopicActionCollect(memberId);
        return memberClient.calcProfileByForm(memberId, new Gson().toJson(topicActionStats));
    }
    //11:个人信息(通过Json/传递)
    @GetMapping("/{id}/profile/json")
    public ResponseEntity<MemberProfileVo> getMemberProfileJson(@PathVariable("id") long memberId){
        Map<ForumActionEnum, Long> topicActionStats = actionLogClient.getTopicActionCollect(memberId);
        return memberClient.calcProfileByJson(memberId, topicActionStats);
    }
    
    //2:个人头像
    @GetMapping("/{id}/avatar")
    public String getAvatar(@PathVariable("id") long memberId){
        ResponseEntity<String> rs = memberClient.getAvatar(memberId);
        return Optional.ofNullable(rs.getBody()).orElse("/ico/avatar/empty.png");
    }
    
    //3:登录
    @PostMapping(value="/checkIn", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<MemberVo> login(
            @RequestParam("names") String names,
            @RequestParam("password") String password,
            @RequestParam("token") String token,
            @RequestParam("ip")String ipAddr){
        try {
            return memberClient.login(names, password, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-login]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.notFound().build();
    }
    
    //4:注销
    @PostMapping(value="/checkOut", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<String> logout(
            @RequestParam("id") long memberId,
            @RequestParam("names") String names,
            @RequestParam("token") String token,
            @RequestParam("ip")String ipAddr){
        try {
            return memberClient.logout(memberId, names, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-logout]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.badRequest().build();
    }
    
    //5:注册
    @PostMapping(value="/registe", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<MemberVo> registe(
            @RequestParam("names") String names,
            @RequestParam("password") String password,
            @RequestParam(value="nickname", required=false, defaultValue="-") String nickname,
            @RequestParam(value="invite", required=false, defaultValue="") String inviteCode,
            @RequestParam("token") String token,
            @RequestParam("ip")String ipAddr){
        try {
            return memberClient.registe(names, password, nickname, inviteCode, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-registe]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.notFound().build();
    }
    
    //6:检查注册邀请码是否可用
    @GetMapping("/invite/{code}")
    public CommonResponseVo getInviteCode(@PathVariable("code") String inviteCode){
        ResponseEntity<CommonResponseVo> rs = memberClient.getInviteCode(inviteCode);
        return Optional.ofNullable(rs.getBody()).orElse(new CommonResponseVo());
    }
    
    //7:检查会员帐号是否可用
    @GetMapping("/detection/{names}")
    public ResponseEntity<String> getUnionNames(@PathVariable("names") String names){
        try {
            return memberClient.getUnionNames(names);
        }catch (Exception e){
            logger.error("[nest-registe-detection]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.notFound().build(); //------------------------------------------------------------------->
    }
    
    //12:编辑个人信息
    @PutMapping(value="/{id}/profile/modify", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<String> editProfile(
            @PathVariable("id") long memberId,
            @RequestParam("signature") String signatureContent,
            @RequestParam("nickname") String nickname,
            @RequestParam("token") String token,
            @RequestParam("ip")String ipAddr){
        try {
            return memberClient.editProfile(memberId, signatureContent, nickname, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-profile-reset]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.badRequest().build();
    }
    
    //13:编辑密码
    @PutMapping(value="/{id}/password/modify", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<String> editPassword(@PathVariable("id") long memberId,
                    @RequestParam("original") String oldPswd,
                    @RequestParam("current") String newPswd,
                    @RequestParam("token") String token,
                    @RequestParam("ip")String ipAddr){
        try {
            return memberClient.editPassword(memberId, oldPswd, newPswd, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-pswd-reset]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.badRequest().build();
    }
    
    //14:重置会员密码
    @PutMapping(value="/{id}/password/reset", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<String> resetPassword(@PathVariable("id") long memberId,
                     @RequestParam("current") String newPswd,
                     @RequestParam("token") String token,
                     @RequestParam("ip")String ipAddr){
        try {
            return memberClient.resetPassword(memberId, newPswd, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-pswd-reset]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.badRequest().build();
    }
    
    //15:编辑头像
    @PutMapping(value="/{id}/avatar/modify", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<String> editAvatar(@PathVariable("id") long memberId,
                   @RequestParam("avatar") String avtarFileName,
                   @RequestParam("app_domain") String appLocalDomain,
                   @RequestParam("app_avatar_direct") String avatarDefaultDirect,
                   @RequestParam("token") String token,
                   @RequestParam("ip")String ipAddr){
        try {
            return memberClient.editAvatar(memberId, avtarFileName, appLocalDomain, avatarDefaultDirect, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-avatar-update]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.badRequest().build();
    }
    
    //16:社会化信息
    @GetMapping("/{id}/social")
    public MemberSocialVo getSocial(@PathVariable("id") long memberId){
        ResponseEntity<MemberSocialVo> rs = memberClient.getSocial(memberId);
        return Optional.ofNullable(rs.getBody()).orElse(new MemberSocialVo());
    }
    
    //17:查询社会化信息
    @PostMapping(value="/social/query", consumes="application/x-www-form-urlencoded")
    public MemberSocialVo getSocialByMail(@RequestParam("names") String names, @RequestParam("mail") String email){
        ResponseEntity<MemberSocialVo> rs = memberClient.getSocialByMail(names, email);
        return Optional.ofNullable(rs.getBody()).orElse(new MemberSocialVo());
    }
    
    //18:编辑社会化信息
    @PutMapping(value="/{id}/social/modify", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<String> editSocial(
            @PathVariable("id")long memberId,
            @RequestParam("names") String names,
            @RequestParam("record") long recordId,
            @RequestParam("weibo") String weibo,
            @RequestParam("weixin") String weixin,
            @RequestParam("qq") String qq,
            @RequestParam("mail") String email,
            @RequestParam("token") String token,
            @RequestParam("ip")String ipAddr){
        try {
            return memberClient.editSocial(memberId, names, recordId, weibo, weixin, qq, email, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-social-update]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.badRequest().build();
    }
    
    //19:新增社会化信息
    @PostMapping(value="/{id}/social/create", consumes="application/x-www-form-urlencoded")
    public ResponseEntity<MemberSocialVo> newSocial(
            @PathVariable("id")long memberId,
            @RequestParam("names") String names,
            @RequestParam("weibo") String weibo,
            @RequestParam("weixin") String weixin,
            @RequestParam("qq") String qq,
            @RequestParam("mail") String email,
            @RequestParam("token") String token,
            @RequestParam("ip")String ipAddr){
        try {
            return memberClient.newSocial(memberId, names, weibo, weixin, qq, email, token, ipAddr);
        }catch (Exception e){
            logger.error("[nest-member-social-create]ResponseEntity exception:"+e.getMessage());
        }
        return ResponseEntity.notFound().build();
    }
    
    //20:社区标兵
    @GetMapping("/model/stats")
    public List<MemberModelVo> getBrandMemberModel(@RequestParam(value="size", required=false, defaultValue="10") int showSize){
        return actionLogClient.getBrandMemberModel(showSize);
    }
    
    //21:底部的会员统计汇总
    @GetMapping("/collect")
    public MemberStatsCollectVo getBoardStatsCollect(@RequestParam(value="cycle", required=false, defaultValue="30") int statsCycle){
        ResponseEntity<MemberStatsCollectVo> rs = memberClient.getBoardStatsCollect(statsCycle);
        return Optional.ofNullable(rs.getBody()).orElse(new MemberStatsCollectVo());
    }
    
    //22:上次登录记录
    @GetMapping("/login/lastrecord/{id}/{names}")
    public MemberRecordVo getLastLoginRecord(@PathVariable("id") long memberId, @PathVariable("names") String names){
        ResponseEntity<MemberRecordVo> rs = memberClient.getLastLoginRecord(memberId, names);
        return Optional.ofNullable(rs.getBody()).orElse(new MemberRecordVo());
    }
    
    //23:
    @GetMapping("/actionrecord/{names}")
    public List<MemberRecordVo> getActionRecords(@PathVariable("names") String names, @RequestParam("size") int showSize){
        return memberClient.getActionRecords(names, showSize);
    }
    
    /*会员的操作记录
    @GET
    @Path("/{id}/history/{page}/{number}")
    @Produces({MediaType.APPLICATION_JSON })
    public Response getMemberActionHistory(@PathParam("id") long memberId, @PathParam("page") int page, @PathParam("number") int pageSize){
        Page<TopicActionCollectionReplica> rs = topicActionCollectionService.getByMember(memberId, new PageRequest(page, pageSize));
        return ResponseResult.PageResultBuilder.<ThreadsRecordVo,TopicActionCollectionReplica>getInstance(page, pageSize).from(rs.getTotalElements(), rs.getResult()).build(new TopicActionRecordVoMapperEntity()).toJson();
    }
    //会员收藏的话题
    @GET
    @Path("/{id}/topic/favorite/{page}/{number}")
    @Produces({MediaType.APPLICATION_JSON })
    public Response getMemberFavoriteTopic(@PathParam("id") long memberId, @PathParam("page") int page, @PathParam("number") int pageSize){
        Page<TopicActionCollectionReplica> rs = topicActionCollectionService.getAllByMemberAction(memberId, ForumActionEnum.TOPIC_FAVORITE, new PageRequest(page, pageSize));
        return ResponseResult.PageResultBuilder.<ThreadsRecordVo,TopicActionCollectionReplica>getInstance(page, pageSize).from(rs.getTotalElements(), rs.getResult()).build(new TopicActionRecordVoMapperEntity()).toJson();
    }
    //会员点赞的话题
    @GET
    @Path("/{id}/topic/like/{page}/{number}")
    @Produces({MediaType.APPLICATION_JSON })
    public Response getMemberLickTopic(@PathParam("id") long memberId, @PathParam("page") int page, @PathParam("number") int pageSize){
        Page<TopicActionCollectionReplica> rs = topicActionCollectionService.getAllByMemberAction(memberId, ForumActionEnum.TOPIC_LIKED, new PageRequest(page, pageSize));
        return ResponseResult.PageResultBuilder.<ThreadsRecordVo,TopicActionCollectionReplica>getInstance(page, pageSize).from(rs.getTotalElements(), rs.getResult()).build(new TopicActionRecordVoMapperEntity()).toJson();
    }*/
    
    //27:获取客户端IP
    @GetMapping("/ip/query")
    public Map<String,String> getClientRequestIp(HttpServletRequest request){
        Map<String,String> data = Map.of("ip", "127.0.0.1");
        return data;
        //return memberClient.getClientRequestIp(request);
    }
}